#!/bin/bash

# Asurada SSO客户端部署脚本

echo "=========================================="
echo "    Asurada SSO 客户端部署脚本"
echo "=========================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 显示帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  local     本地开发环境部署"
    echo "  docker    Docker容器部署"
    echo "  build     仅构建项目"
    echo "  clean     清理构建文件"
    echo "  test      运行测试"
    echo "  help      显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 local    # 本地开发环境启动"
    echo "  $0 docker   # Docker环境部署"
    echo "  $0 build    # 构建项目"
    echo ""
}

# 检查依赖
check_dependencies() {
    echo "检查依赖环境..."
    
    # 检查Java
    if ! command -v java &> /dev/null; then
        echo -e "${RED}❌ 错误: 未找到Java环境，请安装JDK 21${NC}"
        return 1
    fi
    
    JAVA_VERSION=$(java -version 2>&1 | head -n 1 | cut -d'"' -f2 | cut -d'.' -f1)
    if [ "$JAVA_VERSION" -lt 21 ]; then
        echo -e "${RED}❌ 错误: 需要JDK 21或更高版本，当前版本: $JAVA_VERSION${NC}"
        return 1
    fi
    echo -e "${GREEN}✅ Java环境检查通过${NC}"
    
    # 检查Maven
    if ! command -v mvn &> /dev/null; then
        echo -e "${RED}❌ 错误: 未找到Maven，请安装Maven 3.6+${NC}"
        return 1
    fi
    echo -e "${GREEN}✅ Maven环境检查通过${NC}"
    
    return 0
}

# 检查Docker依赖
check_docker_dependencies() {
    echo "检查Docker环境..."
    
    if ! command -v docker &> /dev/null; then
        echo -e "${RED}❌ 错误: 未找到Docker，请安装Docker${NC}"
        return 1
    fi
    echo -e "${GREEN}✅ Docker环境检查通过${NC}"
    
    if ! command -v docker-compose &> /dev/null; then
        echo -e "${RED}❌ 错误: 未找到Docker Compose，请安装Docker Compose${NC}"
        return 1
    fi
    echo -e "${GREEN}✅ Docker Compose环境检查通过${NC}"
    
    return 0
}

# 构建项目
build_project() {
    echo "开始构建项目..."
    
    if ! check_dependencies; then
        return 1
    fi
    
    echo "清理之前的构建..."
    mvn clean -q
    
    echo "编译项目..."
    mvn compile -q
    if [ $? -ne 0 ]; then
        echo -e "${RED}❌ 编译失败${NC}"
        return 1
    fi
    
    echo "打包项目..."
    mvn package -DskipTests -q
    if [ $? -ne 0 ]; then
        echo -e "${RED}❌ 打包失败${NC}"
        return 1
    fi
    
    echo -e "${GREEN}✅ 项目构建成功${NC}"
    return 0
}

# 本地部署
deploy_local() {
    echo "开始本地环境部署..."
    
    if ! build_project; then
        return 1
    fi
    
    # 检查Redis
    echo "检查Redis连接..."
    if command -v redis-cli &> /dev/null; then
        if ! redis-cli ping > /dev/null 2>&1; then
            echo -e "${YELLOW}⚠️  警告: Redis连接失败，尝试启动Redis...${NC}"
            if command -v redis-server &> /dev/null; then
                redis-server --daemonize yes
                sleep 2
                if redis-cli ping > /dev/null 2>&1; then
                    echo -e "${GREEN}✅ Redis启动成功${NC}"
                else
                    echo -e "${RED}❌ Redis启动失败，请手动启动Redis服务${NC}"
                fi
            else
                echo -e "${RED}❌ 未找到Redis服务，请安装并启动Redis${NC}"
            fi
        else
            echo -e "${GREEN}✅ Redis连接正常${NC}"
        fi
    fi
    
    echo ""
    echo "启动应用..."
    echo "应用将在以下地址运行:"
    echo -e "${BLUE}  - 首页: http://localhost:8081${NC}"
    echo -e "${BLUE}  - 登录页面: http://localhost:8081/login${NC}"
    echo -e "${BLUE}  - 受保护页面: http://localhost:8081/protected${NC}"
    echo -e "${BLUE}  - 个人信息: http://localhost:8081/profile${NC}"
    echo ""
    echo "按 Ctrl+C 停止应用"
    echo "=========================================="
    
    # 启动应用
    mvn spring-boot:run
}

# Docker部署
deploy_docker() {
    echo "开始Docker环境部署..."
    
    if ! check_docker_dependencies; then
        return 1
    fi
    
    echo "停止现有容器..."
    docker-compose down
    
    echo "构建Docker镜像..."
    docker-compose build
    if [ $? -ne 0 ]; then
        echo -e "${RED}❌ Docker镜像构建失败${NC}"
        return 1
    fi
    
    echo "启动Docker容器..."
    docker-compose up -d
    if [ $? -ne 0 ]; then
        echo -e "${RED}❌ Docker容器启动失败${NC}"
        return 1
    fi
    
    echo -e "${GREEN}✅ Docker部署成功${NC}"
    echo ""
    echo "应用信息:"
    echo -e "${BLUE}  - 首页: http://localhost:8081${NC}"
    echo -e "${BLUE}  - 健康检查: http://localhost:8081/actuator/health${NC}"
    echo -e "${BLUE}  - Redis: localhost:6379${NC}"
    echo ""
    echo "查看日志: docker-compose logs -f"
    echo "停止服务: docker-compose down"
    
    # 等待服务启动
    echo "等待服务启动..."
    sleep 10
    
    # 检查服务状态
    if curl -s http://localhost:8081/actuator/health > /dev/null; then
        echo -e "${GREEN}✅ 服务启动成功${NC}"
    else
        echo -e "${YELLOW}⚠️  服务可能还在启动中，请稍后检查${NC}"
    fi
}

# 清理构建文件
clean_project() {
    echo "清理构建文件..."
    
    if [ -f "pom.xml" ]; then
        mvn clean -q
        echo -e "${GREEN}✅ Maven构建文件已清理${NC}"
    fi
    
    if [ -f "docker-compose.yml" ]; then
        docker-compose down 2>/dev/null
        docker system prune -f 2>/dev/null
        echo -e "${GREEN}✅ Docker资源已清理${NC}"
    fi
    
    # 清理日志文件
    if [ -d "logs" ]; then
        rm -rf logs/*
        echo -e "${GREEN}✅ 日志文件已清理${NC}"
    fi
}

# 运行测试
run_tests() {
    echo "运行项目测试..."
    
    if ! check_dependencies; then
        return 1
    fi
    
    # 运行Maven测试
    mvn test
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ 所有测试通过${NC}"
    else
        echo -e "${RED}❌ 测试失败${NC}"
        return 1
    fi
    
    # 运行功能测试脚本
    if [ -f "test-client.sh" ]; then
        echo ""
        echo "运行功能测试..."
        ./test-client.sh
    fi
}

# 主函数
main() {
    case "$1" in
        "local")
            deploy_local
            ;;
        "docker")
            deploy_docker
            ;;
        "build")
            build_project
            ;;
        "clean")
            clean_project
            ;;
        "test")
            run_tests
            ;;
        "help"|"--help"|"-h")
            show_help
            ;;
        "")
            echo -e "${YELLOW}请指定部署方式，使用 '$0 help' 查看帮助${NC}"
            show_help
            ;;
        *)
            echo -e "${RED}未知选项: $1${NC}"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"